package kr.mir.util.parser;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import kr.mir.util.config.Config;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class XmlParser {

	private File file = null;
	private Element root = null;
	private Config config = null;

	public XmlParser(String fileName) {
		file = new File(fileName);
		init();
	}
	
	private void init() {
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(file);
			
			root = doc.getRootElement();
			config = new Config();
			insertElement(root, config);
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void insertElement(Element element, Config config) {
		// TODO Auto-generated method stub
		config.setType(element.getName());
		
		Iterator<Attribute> iter = element.getAttributes().iterator();
		while(iter.hasNext()) {
			Attribute attr = iter.next();
			config.setValue(attr.getName(), attr.getValue());
		}
		
		List<Element> list = element.getChildren();
		if(!list.isEmpty()) {
			Iterator<Element> childIter = list.iterator();
			while(childIter.hasNext()) {
				Element childElement = childIter.next();
				Config childConfig = new Config();
				insertElement(childElement, childConfig);
				
				config.add(childConfig);
			}
		}
	}
	
	
	public Config getConfig() {
		return config;
	}
}
